<?php

namespace longhu\services\easywechat\client;

use EasyWeChat\MiniApp\Application;
use longhu\exceptions\FailedException;
use myshop\common\dao\ConfigValueDao;
use Swoole\Exception;

class WechatClient
{

    protected $client;
    protected $app;
    protected $config;

    public function __construct(array $config)
    {
        $this->config = $config;
        $this->app = new Application($config);
        $this->client = $this->app->getClient();
    }

    public static function create()
    {
        return new self(self::getConfig());
    }



    public static function getConfig()
    {
        /** @var ConfigValueDao $make */
        $make = app()->make(ConfigValueDao::class);
        $wechat = $make->more([
            'routine_appId', 'routine_appsecret'
        ], 0);
        return [
            'app_id'=>$wechat['routine_appId'],
            'secret'=>$wechat['routine_appsecret'],
            'aes_key'=>'123456',
            'token'=>'longhuadmin',
            'http'=>[
                'throw'  => true, // 状态码非 200、300 时是否抛出异常，默认为开启
                'timeout' => 5.0,
                'retry' => true,
            ]
        ];
    }

    public function getClient()
    {
        return $this->client;
    }

    public function getApp()
    {
        return $this->app;
    }

    /**
     * 小程序登录
     * @param string $code
     * @return array|mixed[]
     * @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
     */
    public function authLogin(string $code):array
    {
        $result = $this->app->getUtils()->codeToSession($code);
        return $result;
    }

    public function getAccessToken():array
    {
        $param = [
            'grant_type'=>'client_credential',
            'appid'=>$this->config['app_id'],
            'secret'=>$this->config['secret'],
        ];
        $res = $this->client->get("https://api.weixin.qq.com/cgi-bin/token",$param)->toArray();
        $token = $res['access_token'];
        $expires_in = $res['expires_in'];
       // $token = "81_moVDk8Ckp-aCnY2afsWqo667YhRhrqpRfY4UYH0vjG6-c2zGv_K6hxfAN6WAKwhSLN1VuVg3FnWRDsVm-OVeztmbUgR0WtgbpikbbUvw0H6l1F3fHknm3BNJuQ8OJEeAGAZUP";
        //dump($token);exit;
        cache(MpToken::TOKEN_KEY,$token,7200-600);
      //  $this->app->setAccessToken(new MpToken());
        return [
            'access_token'=>$token,
            'expires_in'=>$expires_in
        ];
    }

    /**
     * @return mixed|object|\think\App
     */
    public function checkToken()
    {
        $token =  cache(MpToken::TOKEN_KEY);
        if(empty($token)){
            $res = $this->getAccessToken();
            $token = $res['access_token'];
        }
        if(empty($token)){
            throw new FailedException('TOKEN ERROR : 获取TOKEN失败');
        }
        return $token;
    }



    public function checkSessionKey(string $openid = '')
    {

    }

    public function decryptData(string $iv,string $session_key,string $encryptedData)
    {
        return  $this->app->getUtils()->decryptSession($session_key, $iv, $encryptedData);
    }


}